// 后台数据
let dataInfo = [
  { name: "English chan", money: 392001 },
  { name: "alex chan", money: 568932 },
  { name: "melon chan", money: 698756 },
  { name: "Clare Langner", money: 292489 },
  { name: "Abigail Rice", money: 953957 },
  { name: "Clarice Dias", money: 168472 },
  { name: "Vernon Lucas", money: 718225 },
  { name: "Nina Schmidt", money: 889147 },
];

// 导航栏
let nav = document.querySelector(".nav-btn");
let aside = document.querySelector(".aside");
nav.onclick = () => {
  aside.classList.toggle("active");
};

let ul = document.querySelector(".left ul");
let count = 0;
let list = document.querySelector(".list");
let totalAmount = document.querySelector(".total-amount");
// 存放页面上的添加的账户信息
let pageData = [];

// 渲染账户数据
function renderHtml() {
  let listItems = pageData.map((item) => {
    return `
    <div class="right-title">
      <strong>${item.name}</strong>
      <span>${thousands(item.money)}</span>
    </div>
    `;
  });
  list.innerHTML = listItems.join("");
}

ul.onclick = (e) => {
  // 添加账户
  if (e.target.className === "add") {
    if (count !== dataInfo.length) {
      pageData.push(dataInfo[count]);
      renderHtml();
      count++;
    }
  }
  // 资金翻倍
  if (e.target.className === "doubling") {
    pageData = pageData.map((ele) => ({ ...ele, money: ele.money * 2 }));
    renderHtml();
  }
  // 查询百万富翁
  if (e.target.className === "query") {
    pageData = pageData.filter((ele) => ele.money >= 100_0000);
    renderHtml();
  }
  // 财富榜（从大到小排序）
  if (e.target.className === "wealth-list") {
    pageData = pageData.sort((a, b) => b.money - a.money);
    renderHtml();
  }
  // 计算总额
  if (e.target.className === "total") {
    if (pageData.length) {
      let total = pageData.reduce((prev, item) => prev + item.money, 0);
      totalAmount.innerHTML = `
      <strong>Total-num:</strong>
      <span>${thousands(total)}</span>`;
    }
  }
};

// 货币处理
function thousands(money) {
  // 方法一:
  /* return money
    .toFixed(2)
    .toString()
    .replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
 */
  // 方法二
  // let res = money.toLocaleString();
  // return "$" + res + ".00";

  // 方法三:
  let arr = money.toString().split("");
  let newArr = [];
  let count = 0;
  let res;
  for (let i = arr.length - 1; i >= 0; i--) {
    count++;
    newArr.unshift(arr[i]);
    if (count % 3 === 0 && i != 0) {
      newArr.unshift(",");
    }
  }

  return "$" + newArr.join("") + ".00";
}
